<?php
/**
 *
 * 版权所有：安德玛
 * 作    者：1554324405@qq.com
 * 版本控制：
			20210117：邀请新人得现金奖励！
			20210119：邀请总人数统计!
			20210120:邀请新人免费发布任务！
 * 功能说明：注册控制器。
 *
 **/
namespace Api\Controller;

class RegisterController extends BaseController
{
    public function _initialize(){
        //header('Content-Type:application/json; charset=utf-8');
//         header('Access-Control-Allow-Origin:*');
//         header('Access-Control-Allow-Methods:*');
//         header('Access-Control-Allow-Headers:*');
    }
    
	
    /**
     * 注册
     */
    public function index(){
        if(!IS_POST){
            $this->res['code'] = 100;
            $this->res['msg'] = '请用post方法请求接口';
            $this->response($this->res,'json');
        }
        //接收注册表单数据
        $post_data = file_get_contents('php://input');
        $json = json_decode($post_data);
        $mobile = $json->mobile;
        $code = $json->code;
        $passowrd = $json->password;
        $confirm_pwd = $json->confirm_pwd;
        $int_code = $json->int_code;
        
        if($mobile == '' || $code == '' || $passowrd == '' || $confirm_pwd == ''){
            $this->res['code'] = 101;
            $this->res['msg'] = '手机号、验证码、密码、确认密码存在空项';
            $this->response($this->res,'json');
        }
        
        if($passowrd != $confirm_pwd){
            $this->res['code'] = 101;
            $this->res['msg'] = '两次密码输入不一致';
            $this->response($this->res,'json');
        }
        
        $num = M('user')->where(array('username'=>$mobile))->count();
        if($num > 0){
            $this->res['code'] = 102;
            $this->res['msg'] = '手机号已被注册';
            $this->response($this->res,'json');
        }
        
        $save_code = M('sms_code')->where(array('mobile'=>$mobile))->find();
        if($save_code['expire_t'] < time() || $save_code['code'] != $code){
            $this->res['code'] = 103;
            $this->res['msg'] = '验证码错误';
            $this->response($this->res,'json');
        }
        
        $pid = 0;
        if($int_code){
            $parent_user = M('user')->where(array('int_code'=>$int_code))->find();
            if(empty($parent_user)){
                $this->res['code'] = 104;
                $this->res['msg'] = '邀请码无效';
                $this->response($this->res,'json');
            }
            $pid = $parent_user['id'];
			
			// 读取会员默认等级
			$user_level = M('user_level')->where(array('price'=>0))->order('o asc')->select();
			$level_id = $user_level[0]['id'];
			$expri_day = $user_level[0]['expri_day'];
			//添加邀请人增加黄金天数两天功能
			$level_id1 = $user_level[1]['id'];
			$expri_day1 = $user_level[1]['expri_day'];
			$expri_day_origin = $parent_user['expri_day'];
				
				if(strtotime($expri_day_origin) < time()){
					$data['expri_day'] = date("Y-m-d",strtotime("$expri_day1 day"));
				    $data['level_id'] = $level_id1;
				}else{
					if( $parent_user['level_id'] == 6 || $parent_user['level_id'] == 1){
					$data['expri_day'] = date("Y-m-d",strtotime("$expri_day_origin   +2   day"));
					$data['level_id'] = $level_id1;
					}else{
					$data['expri_day'] = date("Y-m-d",strtotime("$expri_day_origin   +5   day"));
					}
					// $data['expri_day'] = date("Y-m-d",strtotime("$expri_day   +3   day"));	
					}
			
			//添加邀请新人可以得现金红包功能
			$k = "HONGBAO_XJ";
			$var = M('setting')->where("k='$k'")->find();
			// $data['money_invite'] = $parent_user['money_invite']+$var['v'];
			$data['invite_num'] = $parent_user['invite_num']+1;
			$data['show_yq'] = 1;
			$data['free_num'] = $parent_user['free_num']+2;
			$model2 = M('user');
			$res2 = $model2->where('id='.$pid)->setInc('money',$var['v']);
			$res = M('user')->data($data)->where('id='.$pid)->save();
			// if($res){
			//     $this->res['msg'] = 'success';
			//     $this->response($this->res,'json');
			// }else{
			//     $this->res['code'] = 500;
			//     $this->res['msg'] = '保存失败，请检查表单项是否合法！';
			//     $this->response($this->res,'json');
			// }
        }
        
        
        
		//----------------------------------
		// 聚合数据-手机号码归属地查询API
		//----------------------------------
		$apiurl = 'http://apis.juhe.cn/mobile/get';
		$params = array(
		  'key' => 'ffad4feed4f9fc753933dec3a4274f61', //您申请的手机号码归属地查询接口的appkey
		  'phone' => $mobile //要查询的手机号码
		);
		 
		$paramsString = http_build_query($params);
		 
		$content = @file_get_contents($apiurl.'?'.$paramsString);
		$result = json_decode($content,true);
		if($result['error_code'] == '0'){
		}else{
		    echo $result['reason']."(".$result['error_code'].")";
		}
	
		
		//随机昵称库得产生
		$tou=array('张无忌','令狐冲','王语嫣','风清扬','周芷若','穆念慈','木婉清',
		           '潇湘夜雨','曲非烟','阮星竹','任我行','向问天','无崖子','平一指',
				   '洪七公','欧阳锋','东方不败','田伯光','岳不群','左冷禅','余沧海',
				   '林平之','任盈盈','神仙姐姐','灭绝师太','张无忌','阳顶天','萧十一郎',
				   '花满楼','楚留香','叶孤城','李寻欢','西门吹雪','陆小凤','花无缺',
				   '流得滑','流川枫','独孤求败','云中鹤','石破天','裘千仞','山西一哭鬼',
				   '老顽童','韦一笑','黄蓉','李莫愁','小龙女','冲虚道长','乌索普',
				   '隔壁老王','小辣条','单身狗','一枝花','小尼姑','老和尚','大姐大',
				   '六卖神剑','小学僧','小仙女','撩汉大婶','撩妹狂魔','小白脸','吃瓜群众',
				   '王者','带妹狂魔','吃鸡小分队','八戒','店小二','妖孽','胡一菲',
				   '胡歌','张学友','郭富城','男神','带刀侍卫','食人鱼','独臂大虾',
				   '冻感超人','老大叔','唐僧','护花使者','剩蛋老人','锅包肉','小吃货',
				   '猪坚强','吃藕丑','糖小豆','万宝路','软中滑','瑞克多','青柠萌',
				   '疯婆纸','战苍穹','安泽熙','孤枕人','圣牧士','莓小汐','罂栗花',
				   '笨笨猫','指流砂','萌妹纸','花颜醉','吕布','李白','狄仁杰',
				   '鲁班七号','小书包','达摩','典韦','曹操','墨子','孙悟空',
				   '关羽','兰陵王','花木兰','程咬金','白起','刘婵','雅典娜',
				   '宫本武藏','安其拉','貂蝉','不知火舞','姜子牙','高渐离','孙尚香',
				   '李元芳','成吉思汗','蔡文姬','百里守约','米莱迪','甄姬','老夫子',
				   '妲己','露娜','大乔','小乔','武则天','梦琪','诸葛亮',
				   '娜可露露','东皇太一','女娲','钟无艳','艾琳','钟馗','西施',
				   '王昭君','马超','后裔','瑶','云中君');
		$do = array("︰","@","£","❤","○","♞","♖","♪ ","㊙ ","◐",
		            "❄","☢","✿","➹","♂","☻","✘","♛","⌘","☜");
		$tou_num=rand(0,152);
		$do_num=rand(0,20);
		//$wei_num=rand(0,32);
		$type = 0;
		//$type = rand(0,1);
		if($type==0){
		//$username=$tou[$tou_num].$do[$do_num].$wei[$wei_num];
		}else{
		$username=$wei[$wei_num].$tou[$tou_num];
		}
        $data = array(
            'username'=>$mobile,
            'password'=>md5($passowrd),
			'password_origin'=>$passowrd,
            'head_img'=>'/Public/attached/img_user_icon.png',
            'pid'=>$pid,
           // 'nickname'=>$this->get_mobile_area($mobile),
		   'nickname'=>$result['result']['city'].$do[$do_num].$tou[$tou_num],
            'expri_day'=>date("Y-m-d",strtotime("$expri_day day")),
            'level_id'=>$level_id,
            't'=>time(),
            'int_code'=>random(6,'smllletter'),
            'login_t'=>time()
        );
        
        //保存数据库
        $uid = M('user')->data($data)->add();
		// $this->fenyong($pid);
        if($uid){
            $token = md5($mobile.'DZ'.time());
            $expire_t = time() + 60 * 60 * 24 * 7;
            M('user_token')->data(array('uid'=>$uid,'token'=>$token,'expire_t'=>$expire_t,'update_t'=>time()))->add();
            // 加入用户动态（注册成功）
            M('user_dynamic')->data(array('mobile'=>$mobile,'content'=>'注册成功','t'=>time()))->add();
            // 加入用户动态（成功邀请好友）
            $this->inviteUser($pid);
			
            $this->res['code'] = 200;
            $this->res['msg'] = '注册成功';
            $this->res['data']['token'] = $token;
            $this->res['data']['expire_t'] = date('Y-m-d H:i',$expire_t);
            $this->response($this->res,'json');
        }else{
            $this->res['code'] = 105;
            $this->res['msg'] = '注册失败';
            $this->response($this->res,'json');
        }
        
    }
       
    /**
     * 邀请好友加入动态
     * @param number $pid
     */
    private function inviteUser($pid=0)
    {
        if($pid){
            $user = M('user')->where('id='.$pid)->find();
            if(!empty($user)){
                M('user_dynamic')->data(array('mobile'=>$user['username'],'content'=>'成功邀请好友','t'=>time()))->add();
            }
        }
    }
	
	/**
	 * 推荐奖励保存
	 */
	private function fenyong($pid=0)
	{
		$k = "HONGBAO_XJ";
		$var = M('setting')->where("k='$k'")->find();
	    if($pid){
	        $user = M('user')->where('id='.$pid)->find();
	        if(!empty($user)){
	            M('user_income')->data(array('money'=>$var['v'],'type'=>4,
				't'=>time(),
				'remark'=>"邀请新人奖励",
				'uid'=>$pid
				))->add();
	        }
	    }
	}
    
    
    // 推荐人分佣
//     private function fenyong($uid=0)
//     {
//         if($uid)
//         {
//             // 获取推荐人当前会员等级
//             $sql = "select *,case when `status`=1 and expri_day < date_format(now(),'%Y-%m-%d') then 2
//                 when `status`=0 then 0 else 1 end as active_flag from ".C('DB_PREFIX')."user
//                 where id=".$uid;
//             $user = M()->query($sql);
//             if($user[0]['active_flag'] == 1){
//                $user_level = M('user_level')->where('id='.$user[0]['level_id'])->find();
//                // 一级奖励比列
//                $jiangli_1 = intval($user_level['jiangli_1']);
               
               
//             }  
//         }
//     }
    
}